﻿namespace EasyWeb.Services
{
    using System;
    using System.ComponentModel.Composition;
    using System.Globalization;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using EasyWeb.Configuration;
    using EasyWeb.Data;
    using EasyWeb.Extensions;

    [Export(typeof(IEWCultureService))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class EWCultureService : IEWCultureService
    {
        public virtual async Task InitializePerRequestAsync()
        {
            var config = await EWExtensionManager.CompositionContainer.GetExportedValue<IEWConfigurationDao>().SelectAsync<EWDefaultLanguageConfiguration>();

            if (!config.UseDefault)
            {
                CultureInfo culture = null;

                if (config.UseBrowserSetting)
                {
                    var languages = HttpContext.Current.Request.UserLanguages;
                    if (languages != null && languages.Length > 0)
                    {
                        var language = languages[0].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
                        culture = CultureInfo.GetCultureInfo(language);
                    }
                }

                if (culture == null)
                {
                    culture = CultureInfo.GetCultureInfo(config.DefaultLanguage);
                }

                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = culture;
            }
        }
    }
}
